"""
装饰器工具
"""

from functools import wraps
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.user import User


def validate_json(required_fields):
    """验证JSON请求体装饰器"""
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not request.is_json:
                return jsonify({'error': '请求必须是JSON格式'}), 400
            
            data = request.get_json()
            if not data:
                return jsonify({'error': '请求体不能为空'}), 400
            
            # 检查必需字段
            missing_fields = []
            for field in required_fields:
                if field not in data or data[field] is None or data[field] == '':
                    missing_fields.append(field)
            
            if missing_fields:
                return jsonify({
                    'error': f'缺少必需字段: {", ".join(missing_fields)}'
                }), 400
            
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def admin_required(f):
    """管理员权限装饰器"""
    @wraps(f)
    @jwt_required()
    def decorated_function(*args, **kwargs):
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or not user.is_admin:
            return jsonify({'error': '需要管理员权限'}), 403
        
        return f(*args, **kwargs)
    return decorated_function


def project_access_required(project_id_param='project_id'):
    """项目访问权限装饰器"""
    def decorator(f):
        @wraps(f)
        @jwt_required()
        def decorated_function(*args, **kwargs):
            current_user_id = get_jwt_identity()
            user = User.query.get(current_user_id)
            
            # 从URL参数或请求数据中获取项目ID
            project_id = kwargs.get(project_id_param)
            if not project_id:
                data = request.get_json() or {}
                project_id = data.get('project_id')
            
            if project_id and not user.can_access_project(project_id):
                return jsonify({'error': '无权限访问该项目'}), 403
            
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def team_member_required(team_id_param='team_id'):
    """团队成员权限装饰器"""
    def decorator(f):
        @wraps(f)
        @jwt_required()
        def decorated_function(*args, **kwargs):
            current_user_id = get_jwt_identity()
            user = User.query.get(current_user_id)
            
            # 从URL参数或请求数据中获取团队ID
            team_id = kwargs.get(team_id_param)
            if not team_id:
                data = request.get_json() or {}
                team_id = data.get('team_id')
            
            if team_id and not user.is_member_of_team(team_id):
                return jsonify({'error': '需要团队成员权限'}), 403
            
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def rate_limit(max_requests=100, window_seconds=3600):
    """API限流装饰器"""
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            # 这里可以实现基于Redis的限流逻辑
            # 简化版本，实际应用中需要更复杂的实现
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def validate_pagination(f):
    """分页参数验证装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        
        if page < 1:
            return jsonify({'error': '页码必须大于0'}), 400
        
        if per_page < 1 or per_page > 100:
            return jsonify({'error': '每页数量必须在1-100之间'}), 400
        
        return f(*args, **kwargs)
    return decorated_function
